var old_ReceiveCode = [];
var old_ReceiveAmount = [];

$(document).ready(function(){
	
	renderDataTable();
	//loadรหัสเรื่อง
	loadOperate();
	manageReceiveCode('plus','default');
	$("#meterService").val("");
	
	$("#refresh").click(function(){
		manageReceiveCode('plus','default');
		$("select#chooseOperate > option[value="+""+"]").prop("selected",true);
		var table = $('#listDataTable').DataTable();
		table.$('tr.selected').removeClass('selected');
	});
});


function editData(requesttype,receivecode,fee,index){
	var table = $('#listDataTable').DataTable();
    table.$('tr').removeClass('selected');
    table.$('tr:eq('+(parseInt(index)-1)+')').addClass('selected');
   
    
	$("#divReceiveRow").html("");
	var meterCode = $("#mCode").val();
	$("#statusUpdate").val(meterCode);
	$("#OldReceiveCode").val(receivecode);
	
	loadOperate(requesttype);
    $.ajax({
		url : 'CS11007Srvl', 
		type : "POST",
		data : {
			process_type : "edit" , 
			requestType :requesttype,
			meterCode:meterCode
		},
		dataType : "json",
		success: function(data){
			
			if(parseInt(data.receive_code.length) == 0){
				
				manageReceiveCode('plus', 'default');
				
			}else{
				for(var i = 0 ; i < parseInt(data.receive_code.length); i++){
					var elemId = (i)+"ReceiveRow" ;
					
					if(i == 0){
						manageReceiveCode('plus', 'default',data.receive_code[i],data.receive_amount[i]);
					}else{
						manageReceiveCode('plus', elemId,data.receive_code[i],data.receive_amount[i]);
					}
				}
			}
		}
	});
 
}

function deleteData(data1,data2,data3,requestType,receiveCode) {
	var table = $('#listDataTable').DataTable();
	$("#dataDelete1").val(requestType);
	$("#dataDelete2").val(receiveCode);
	$('#listDataTable ').on( 'click', function () {
		if ( $(this).hasClass('selected') ) {
			$(this).removeClass('selected');
		}
		else {
			table.$('selected').removeClass('selected');
			$(this).addClass('selected');
		}
	} );
	
	//old_ReceiveCode = receive_code;
	//old_ReceiveAmount = receive_amount;
	document.getElementById("modal_content_confirmModal").innerHTML ="คุณต้องการลบข้อมูลขนาดมาตร:   "+data1
		+"<br>รหัสรับเงิน   : "+data2+"<br>ค่าบริการ(บาท) : " +data3;
	$('#confirmModal').modal();

}

function confirmdeleteData() {
	var requestType = $("#dataDelete1").val();
	var meterCode = $("#oldMeterCode").val();
	
	 $.ajax({
		    type : 'POST',
		    url : "CS11007Srvl",
		    data:{
		    	process_type:"delete",
		    	meterCode : meterCode,
		    	requestType: requestType,
		    	url_address:$("#url_address").val(), 
		    	agent_browser:$("#agent_browser").val()
		    }, 
		    success : function(data) {
		    	location.reload();
		    }
		});
}

function SaveList(){
    var statusUpdate = $("#statusUpdate").val();
	var vainputOperate= $("select#chooseOperate").val();
	var checkReceive =$(".receive-code").val();
	var checkfee =$(".receive-amount").val();
	
	var receive_code = [];
	var receive_amount = [];
	var i = 0;
	$(".receive-code").each(function(){
		receive_code[i] = $(this).val();
	    i++;
	  });
		i = 0;
	$(".receive-amount").each(function(){
		
		receive_amount[i] = $(this).val();
		i++;
	  });
	
	
	if (vainputOperate == "" || checkReceive =="" || checkfee == 0) { 
		document.getElementById("modal_content").innerHTML = "กรุณากรอกข้อมูลให้ครบถ้วน";
		$('#warningModal').modal();
	}else if(isNaN(checkfee) == true) {
		document.getElementById("modal_content").innerHTML = "กรุณากรอกข้อมูลรหัสรับเงินให้ถูกต้อง";
		$('#warningModal').modal();
	}else {
		if (statusUpdate !== "") {
			document.getElementById("modal_content_confirmUpdateModal").innerHTML ="คุณต้องการบันทึกข้อมูลเพื่อดำเนินการเรื่อง:   "+vainputOperate
			+"<br>รหัสรับเงิน   : "+receive_code+"<br>ค่าบริการ(บาท) : " +receive_amount;
			$('#confirmUpdateModal').modal();
			
		} else {
			document.getElementById("modal_content_confirmSaveModal").innerHTML = "คุณต้องการบันทึกข้อมูลเพื่อดำเนินการเรื่อง : "+vainputOperate+
			 " <br> รหัสรับเงิน : " +receive_code +"<br> ต่าบริการ(บาท) "+receive_amount;
			$('#confirmSaveModal').modal();
		}
		
	}
}


function addDataTable(){
	var meterCode = $("#mCode").val();
	var meterSize = $("#mSize").val();
	var meterFee = $("#mService").val();
	var vainputOperate= $("select#chooseOperate").val();
	
	$('#confirmSaveModal').modal('hide');
	var receive_code = [];
	var receive_amount = [];
	var i = 0;
	$(".receive-code").each(function(){
		receive_code[i] = $(this).val();
	    i++;
	  });
		i = 0;
	$(".receive-amount").each(function(){
		
		receive_amount[i] = $(this).val();
		i++;
	  });
	$('#confirmSaveModal').modal('hide');
	
 $.ajax({
	    type : 'POST',
	    url : "CS11007Srvl",
	    data:{
	    	process_type:"insert",
	    	meterCode :meterCode,
	    	meterSize :meterSize,
	    	meterService:meterFee,
	    	operate: vainputOperate, 
	    	receive_code : receive_code,
			receive_amount : receive_amount,
			url_address:$("#url_address").val(), 
			agent_browser:$("#agent_browser").val()
	    }, 
	    success : function(data) {
	    	if(data=="have_requestType"){
	    		document.getElementById("modal_content").innerHTML = "มีรหัสคำร้องนี่แล้ว  กรุณากดปุ่มแก้ไข";
	    		$('#warningModal').modal();
	    	   
	    	}else{
	    		location.reload();
	    	}
	    }
	});
}

function updateDataTable(){
	var meterCode = $("#mCode").val();
	var meterSize = $("#mSize").val();
	var meterFee = $("#mService").val();
	var vainputOperate= $("select#chooseOperate").val();
	 $('#confirmUpdateModal').modal('hide');
	 var receive_code = [];
	 var receive_amount = [];
		var i = 0;
		$(".receive-code").each(function(){
			receive_code[i] = $(this).val();
		    i++;
		    
		  });
			i = 0;
		$(".receive-amount").each(function(){
			
			receive_amount[i] = $(this).val();
			i++;
		  });
	
	 $.ajax({
		    type : 'POST',
		    url : "CS11007Srvl",
		    data:{
		    	process_type:"update",
		    	meterCode :meterCode,
		    	meterSize :meterSize,
		    	meterService:meterFee,
		    	operate: vainputOperate, 
		    	receive_code : receive_code,
				receive_amount : receive_amount,
				old_ReceiveCode : old_ReceiveCode,
				old_ReceiveAmount: old_ReceiveAmount,
				url_address:$("#url_address").val(), 
				agent_browser:$("#agent_browser").val()
		    }, 
		    success : function(data) {
		    	location.reload();
		    }
		});
}


function manageReceiveCode(type, elemId,selectedId,value){
	
	var vnAmount;
	if(isNaN(value)== true){
		vnAmount ="0";
	}else{
		vnAmount = value;
	}

	$.ajax({
				url : "CS11007Srvl?process_type=getReceiveCode",
				type : "POST",
				data : {},
				async : false,
				dataType : 'json',
				success : function(result) {

					var options = '';
					var selected ='';
					options += '<option value="">-- เลือกรหัสรับเงิน --</option>';
					for (var i = 0; i < result.values.length; i++) {
						if(selectedId == result.values[i]){
							selected = "selected=\"selected\"";
						}else{
							selected = "";
						}
						options += '<option value="' + result.values[i] + '" '+selected+'>'
								+ result.messages[i] + '</option>';
					}
					var maxNumber = 0;
					$("#divReceiveRow").children().each(function() {
						var number = parseInt($(this).prop("id"));
						if (number > maxNumber) {
							maxNumber = number;
						}
					});
					$("#inputCountReceiveCode").val((maxNumber + 1));
					if (type == "plus") {

						var rowId = (maxNumber + 1) + "ReceiveRow";
						var html = "";
						
						html += "<div class=\"row\" id=\"" + rowId + "\" style=\"padding-bottom: 3px;\">";
						html += "<div class=\"col-sm-4\" style=\"width:250px;padding-left: 30px;\">";
						html += "<select class=\"receive-code form-control\" id=\"select"
								+ rowId
								+ "\" name=\"receive_code_"
								+ (maxNumber + 1) + "\">";
						html += options;
						html += "</select>";
						html += "</div>";
						html += "<div class=\"col-sm-3\">";
						html += "<input type=\"text\" class=\"receive-amount form-control text-right\" id=\"input"
								+ rowId
								+ "\" name=\"receive_amount_"
								+ (maxNumber + 1)
								+ "\" placeholder=\"จำนวนเงิน\" value=\""+vnAmount+"\" data-container=\"body\" data-toggle=\"popover\" " 
								+"data-placement=\"right\" data-content=\"กรุณากรอกจำนวนเงินให้ถูกต้อง\"/>";
						html += "</div>";
						html += "<div class=\"col-sm-3\">";
						html += "<label for=\"inputPassword3\" class=\"col-sm control-label\">บาท</label>&nbsp;";
						html += "<button type=\"button\" class=\"plus btn btn-primary\"onclick=\"manageReceiveCode('plus','"
								+ rowId
								+ "')\"><i class=\"glyphicon glyphicon-plus\"></i>";
						html += "</button>&nbsp;";
						html += "<button type=\"button\" class=\"minus btn btn-danger\"onclick=\"manageReceiveCode('minus','"
								+ rowId
								+ "')\"><i class=\"glyphicon glyphicon-minus\"></i>";
						html += "</button>";
						html += "</div>";
						html += "</div>";

						if (elemId == "default") {
							$("#divReceiveRow").html(html);
						} else {
							$(html).insertAfter("#" + elemId);
						}

					} else {
						$("#" + elemId).remove();
					}
					var c = $("#divReceiveRow").children();
					if (parseInt(c.length) > 1) {

						$(".minus").prop("disabled", false);
					} else {
						$(".minus").prop("disabled", true);
					}
				}
	});
}

//โหลด ดำเนินการเรื่อง 
function loadOperate(vaCode){
	$.ajax({
		url : 'CS11007Srvl' , 
		type : "POST",
		data : {
			process_type: "getOperate" , 
		},
	//	anync:false,
		dataType:"JSON",
		success: function(data){
			var selected="";
			var options = '';
			options += '<option value="">--เลือกดำเนินการเรื่อง --</option>';
			for (var i = 0; i < data.readId.length; i++) {
				if(vaCode == data.readId[i]){
					selected = "selected='selected'";
				}else{
					selected ="";
				}
				options += '<option value="' + data.readId[i] +'"'+selected+'>' + data.readName[i] +  '</option>';
			}
			 $("select#chooseOperate").html(options);
			
		}
	});
}

//renderDataTable
	function renderDataTable(){
	var meterCode = $("#oldMeterCode").val();
		$('#listDataTable').DataTable( {
			"oLanguage": {
	            "oPaginate": {
	                          "sFirst": "หน้าแรก",// ปุ่มกลับมาหน้าแรก
	                          "sLast": "หนัาสุดท้าย",//ปุ่มไปหน้าสุดท้าย
	                          "sNext": "ถัดไป", //ปุ่มหน้าถัดไป
	                          "sPrevious": "ก่อนหน้า" // ปุ่ม กลับ
	                        	  },
	             "sLengthMenu": "แสดง _MENU_ รายการ ต่อหน้า",  
	             "sZeroRecords": "ไม่พบข้อมูลที่ค้นหา", 
	             "sInfo": "แสดง _START_ ถึง _END_ จากทั้งหมด _TOTAL_ รายการ",
	             "sEmptyTable": "ไม่พบรายการข้อมูล",
	             "sLoadingRecords": "ระบบกำลังประมวลผล กรุณารอซักครู่",
	             "sProcessing": "ประมวลผลข้อมูล",
	             "sInfoEmpty": "ไม่พบรายการข้อมูลที่แสดง",
	             "sInfoFiltered": "(จากทั้งหมด _MAX_ รายการ)",  
	             "sSearch": "ค้นหา :"
	        },
			searching: true,
			"aoColumns" : [ {"sTitle": "ลำดับ", sClass: "alignCenter", sWidth: '3%'},
			                {"sTitle": "รหัสคำร้อง", sClass: "alignRight", sWidth: '20%'},
			                {"sTitle": "รหัสรับเงิน", sClass: "alignRight receive", sWidth: '20%',
			                	"mRender": function ( data, type, full ) {
			                		var html ='';
			                			html += '<div style="padding: 8px 10px;">'+data[0]+'</div>';
			                			for(var i=1 ; i< parseInt(data.length) ;i++){
			                				html += '<hr style="margin-top: 5px;margin-bottom: 0px;border: 0;border-top: 1px solid #eee;"> '+'<div style="padding: 8px 10px;">'+data[i]+'</div>' ;
			                				
			                			}
			                		return  html;
			                		
			                	}},
			                {"sTitle": "ค่าบริการ(บาท)",sClass:"text-right receive",sWidth: '15%', "bSortable": false,
				                	"mRender": function ( data, type, full ) {
				                		var html ='';
				                			html += '<div style="padding: 8px 10px;">'+data[0]+'</div>';
				                			for(var i=1 ; i< parseInt(data.length) ;i++){
				                				html += '<hr style="margin-top: 5px;margin-bottom: 0px;border: 0;border-top: 1px solid #eee;"> '+'<div style="padding: 8px 10px;">'+data[i]+'</div>' ;
				                				
				                			}
				                		return  html;
				                		
				                	}},
			                {"sTitle": "จัดการ", sClass: "alignCenter table-action", sWidth: '10%', "bSortable": false,
			                	"mRender": function ( data, type, full ) { 
			                		return  '<i class="fa fa-wrench" title="แก้ไขข้อมูล" id="editButton" onclick="editData(\'' + full[5] + '\', \'' + full[6] + '\', \'' + full[3] +'\', \''+ full[0] + '\');"></i> '
			                		+ '<i class="fa fa-trash-o" title="ลบข้อมูล" onclick="deleteData(\'' + full[1] + '\', \'' + full[2] + '\', \'' + full[3] +'\', \'' + full[5] + '\', \'' + full[6] +'\');"></i>';
			                	} 
			                }
			               ],
			"bPaginate": true,
			"bInfo" : true,
			"sPaginationType" : "full_numbers",// แสดงตัวแบ่งหน้า
			"bLengthChange": true, // แสดงจำนวน record ที่จะแสดงในตาราง
			"iDisplayLength": 10, // กำหนดค่า default ของจำนวน record 
			"bScrollCollapse": true,
			"aLengthMenu": [
			                [10, 25, 50, 100, -1], // จำนวนที่แสดงในตาราง
			                [10, 25, 50, 100, "ทั้งหมด"] // จำนวนที่ให้เลือก
			 ],
			 "bProcessing": true,  // เขียนโค้ดโดยระบุให้ไปดึงข้อมูลจากไฟล์ getDataTable มาทำงาน โดยเอาข้อมูลที่ได้มาแสดงใน table
			 "iDeferLoading": 11, 
	         "sAjaxSource": "CS11007Srvl?process_type=getDataTable&meterCode="+meterCode+"",
				"drawCallback": function( settings ) {
			    }
		} );
}
	
	
	


